package com.lxk.seckilldemo.controller;

import com.lxk.seckilldemo.pojo.User;
import com.lxk.seckilldemo.service.IGoodsService;
import com.lxk.seckilldemo.service.IUserService;
import com.lxk.seckilldemo.vo.DetailVo;
import com.lxk.seckilldemo.vo.GoodsVo;
import com.lxk.seckilldemo.vo.RespBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("/goods")
public class GoodsController {
    /**
     * windows:qps 791.7
     * ubuntu: qps 229.5
     * 优化
     * 页面缓存 qps 3200
     */
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ThymeleafViewResolver thymeleafViewResolver;
    @RequestMapping(value = "to_list",produces =  "text/html;charset=utf-8")
    @ResponseBody
    public String toList(Model model, User user,HttpServletRequest request, HttpServletResponse response){
        if(user==null) return "login";
        ValueOperations va=redisTemplate.opsForValue();
        String html = (String)va.get("goodsList");
        if(html!=null){
            return html;
        }
        model.addAttribute("user1",user);
        model.addAttribute("goodsList",goodsService.findGoodsVo());
        //手动渲染themleaf
        WebContext webContext=new WebContext(request,response,request.getServletContext(),request.getLocale(),
                model.asMap());
        html=thymeleafViewResolver.getTemplateEngine().process("goods_List",webContext);
        if(html!=null){
            va.set("goodsList",html,60, TimeUnit.SECONDS);

        }
        return html;
    }
    @RequestMapping(value = "/goods_detail/{goodId}", produces =  "text/html;charset=utf-8")
    @ResponseBody
    public String toDetail(@PathVariable Long goodId,Model model,User user,HttpServletRequest request, HttpServletResponse response){
        //缓存有内容，则直接返回
        ValueOperations va=redisTemplate.opsForValue();
        String html = (String)va.get("goods_detail"+goodId);
        if(html!=null){
            return html;
        }
        model.addAttribute("user",user);
        GoodsVo s = goodsService.findGoodsVoById(goodId);
        Date start=s.getStartDate();
        Date end=s.getEndDate();
        Date now=new Date();
        int remain=0;
        int killStatus=0;
        if(now.before(start)){
            remain=(int)(start.getTime()-now.getTime())/1000;
        }else if(now.after(end)) {
            killStatus=2;
            remain=-1;
        }
        else {
            killStatus=1;
            remain=0;
        }
        model.addAttribute("seckillStatus",killStatus);
        model.addAttribute("goods",s);
        model.addAttribute("remainSeconds",remain);
        //手动渲染themleaf
        WebContext webContext=new WebContext(request,response,request.getServletContext(),request.getLocale(),
                model.asMap());
        html=thymeleafViewResolver.getTemplateEngine().process("goods_detail",webContext);
        if(html!=null){
            va.set("goods_detail"+goodId,html,60, TimeUnit.SECONDS);
        }
        return html;
    }


    /**
     *页面静态化
     */
    @RequestMapping("/detail/{goodId}")
    @ResponseBody
    public RespBean toStaticDetail(@PathVariable Long goodId, Model model, User user){
        model.addAttribute("user",user);
        GoodsVo s = goodsService.findGoodsVoById(goodId);
        Date start=s.getStartDate();
        Date end=s.getEndDate();
        Date now=new Date();
        int remain=0;
        int killStatus=0;
        if(now.before(start)){
            remain=(int)(start.getTime()-now.getTime())/1000;
        }else if(now.after(end)) {
            killStatus=2;
            remain=-1;
        }
        else {
            killStatus=1;
            remain=0;
        }
        DetailVo detailVo=new DetailVo();
        detailVo.setUser(user);
        detailVo.setGoodsVo(s);
        detailVo.setKillStatus(killStatus);
        detailVo.setRemain(remain);
        return RespBean.success(detailVo);
    }

}



//    public String toList(HttpServletRequest request, HttpServletResponse response, Model model, @CookieValue("userTicket")String ticket){
//        if(StringUtils.isEmpty(ticket)){
//            return "login";
//        }
//        //User user=(User)session.getAttribute(ticket);
//        User user=userService.getUserByCookies(request,response,ticket);
//        if(user==null) return "login";
//        model.addAttribute("user1",user);
//        return "hetest";
//    }